package com.youxin.chat.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youxin.base.BaseResultCode;
import com.youxin.base.MsgDto;
import com.youxin.chat.basic.dto.constant.FileTypeEnum;
import com.youxin.common.constant.MqConstant;
import com.youxin.common.constant.MsgTypeEnum;
import com.youxin.chat.user.manager.GroupManager;
import com.youxin.chat.user.manager.ImManager;
import com.youxin.chat.user.mapper.GroupMapper;
import com.youxin.chat.user.mapper.GroupMemberMapper;
import com.youxin.chat.user.mapper.UserGroupMapper;
import com.youxin.chat.user.model.Group;
import com.youxin.chat.user.model.GroupMember;
import com.youxin.chat.user.model.UserGroup;
import com.youxin.chat.user.rpc.FileService;
import com.youxin.chat.user.service.UserGroupService;
import com.youxin.chat.user.vo.group.GroupItemVo;
import com.youxin.chat.user.vo.req.GroupNickNameReq;
import com.youxin.chat.user.vo.req.GroupPreferenceReq;
import com.youxin.exception.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.youxin.common.constant.MqConstant.TOPIC_EXCHANGE;

/**
 * description: UserGroupServiceImpl <br>
 * date: 2020/2/28 14:03 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class UserGroupServiceImpl extends ServiceImpl<UserGroupMapper, UserGroup> implements UserGroupService {

    private static final Logger logger = LoggerFactory.getLogger(UserGroupServiceImpl.class);

    @Resource
    private UserGroupMapper userGroupMapper;

    @Resource
    private GroupMapper groupMapper;

    @Resource
    private GroupMemberMapper groupMemberMapper;

    @Resource
    private FileService fileService;

    @Resource
    private ImManager imManager;

    @Resource
    private GroupManager groupManager;

    @Resource
    private AmqpTemplate amqpTemplate;

    @Override
    public void setPreference(String userNo, GroupPreferenceReq userGroupDto) throws SystemException {
        UserGroup userGroup = userGroupMapper.selectByGroupNo(userGroupDto.getGroupNo(), userNo);
        if (userGroup == null) {
            logger.error("群组不存在,groupNo={},userNo={}", userGroupDto.getGroupNo(), userNo);
            throw new SystemException(BaseResultCode.RECORD_NOT_EXISTS, "群组不存在");
        }
        if (userGroupDto.getIsAddressList() != null) {
            userGroup.setIsAddressList(userGroupDto.getIsAddressList());
        }
        if (userGroupDto.getIsTop() != null) {
            userGroup.setIsTop(userGroupDto.getIsTop());
        }
        if (userGroupDto.getNotDisturb() != null) {
            userGroup.setNotDisturb(userGroupDto.getNotDisturb());
        }
        if (!StringUtils.isEmpty(userGroupDto.getBackgroundImg())) {
            userGroup.setBackgroundImg(userGroupDto.getBackgroundImg());
        }
         this.baseMapper.updateById(userGroup);
        if (userGroupDto.getNotDisturb() != null) {
            imManager.setGroupDisturb(userNo, userGroupDto.getGroupNo(), userGroupDto.getNotDisturb());
        }
    }

    @Override
    public List<GroupItemVo> getAddressGroup(String userNo) throws SystemException {
        List<GroupItemVo> list = groupMapper.getAddressGroup(userNo);
        list.stream().forEach(item -> {
            if (!StringUtils.isEmpty(item.getGroupAvatar())) {
                item.setGroupAvatar(fileService.getImageUrl(FileTypeEnum.GROUOP_AVATAR.getType(), item.getGroupAvatar()));
            }
        });
        return list;
    }

    @Override
    public void updateNickName(String userNo, GroupNickNameReq groupNickNameDto) throws SystemException {
        if (StringUtils.isEmpty(groupNickNameDto.getUserNo())) {
            groupNickNameDto.setUserNo(userNo);
        }
        GroupMember groupMember = new GroupMember();
        groupMember.setGroupNo(groupNickNameDto.getGroupNo());
        groupMember.setGroupNote(groupNickNameDto.getGroupNickName());
        groupMember.setGroupUser(groupNickNameDto.getUserNo());

        Group group = groupMapper.getByGroupNo(groupNickNameDto.getGroupNo());
        boolean flag = groupManager.checkOperate(userNo, groupNickNameDto.getGroupNo());

        if (group.getNicknameProtect().equals(0)) {
            if (flag) {
                groupMemberMapper.updateNickName(groupMember);
                sendGroupChangeMsg(groupNickNameDto);
            } else {
                logger.error("已开启群成员保护模式，无法操作,userNo={},groupNo={}", userNo, groupNickNameDto.getGroupNo());
                throw new SystemException(BaseResultCode.HAS_NO_PERMISSION, "群成员昵称保护模式已开启");
            }
        } else {
            if (flag || userNo.equalsIgnoreCase(groupNickNameDto.getUserNo())) {
                groupMemberMapper.updateNickName(groupMember);
                sendGroupChangeMsg(groupNickNameDto);

            } else {
                logger.error("非法操作,userNo={},groupNo={}", userNo, groupNickNameDto.getGroupNo());
                throw new SystemException(BaseResultCode.HAS_NO_PERMISSION, "非法操作");
            }
        }
    }

    private void sendGroupChangeMsg(GroupNickNameReq groupNickNameDto) {
        Map<String, Object> msgMap = new HashMap<>();
        msgMap.put("groupNo", groupNickNameDto.getGroupNo());
        msgMap.put("nickName", groupNickNameDto.getGroupNickName());
        msgMap.put("userNo", groupNickNameDto.getUserNo());

        amqpTemplate.convertAndSend(TOPIC_EXCHANGE,"msg.user", new MsgDto(MsgTypeEnum.NICKNAME_GROUP.getType(), msgMap));
    }
}
